package a66weding.com.jiehuntong.wx;

import java.io.StringReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;


import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.me.MePayActivity;
import a66weding.com.jiehuntong.activity.me.MePaySucceedActivity;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.OrderResultBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.WXbean;
import a66weding.com.jiehuntong.beans.WxremindBean;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.DateUtils;
import a66weding.com.jiehuntong.common.utils.StrUtil;
import a66weding.com.jiehuntong.common.utils.Tools;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;

public class PayActivity extends Activity implements OnNetResultListener {

    private OrderResultBean.DataBean orderResultBean;
    public static String APP_ID = Constants.APP_ID;

    // 商户号
    public static String MCH_ID = Constants.MCH_ID;

    // API密钥，在商户平台设置
    public static String API_KEY = Constants.SIGN;

    private static final String TAG = "MicroMsg.SDKSample.PayActivity";

    private static final int GETRESULT = 5;

    PayReq req;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    Map<String, String> resultunifiedorder;
    StringBuffer sb;

    private WXbean wxb;
    private String subject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        get_MD5Pass();
        orderResultBean = (OrderResultBean.DataBean) getIntent().getSerializableExtra("order");
        subject = getIntent().getStringExtra("subject");
        req = new PayReq();
        sb = new StringBuffer();
        msgApi.registerApp(APP_ID);
        // 生成prepay_id
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();
    }


    private WxremindBean bean;
    private String md5 = "";

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        if (data instanceof WxremindBean) {
            bean = (WxremindBean) data;
            switch (bean.getResCode()) {
                case "0000":
                    Intent intent = new Intent(this, MePaySucceedActivity.class);
                    intent.putExtra("totalPay", StrUtil.floatNumDeal(orderResultBean.getOrder().getDm_TotalMoney()));
                    intent.putExtra("orderNumber", "" + orderResultBean.getOrder().getOrderNumber());
                    intent.putExtra("flag", 1);
                    startActivity(intent);
                    finish();
                    break;
                default:
                    Toast.makeText(PayActivity.this, "数据错误，请联系客服", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
            }
        }

        if (data instanceof WXbean) {
            wxb = (WXbean) data;
            switch (wxb.getResCode()) {
                case "0000":
                    md5 = wxb.getResult();
                    break;
            }
        }
    }

    @Override
    public void onError(ErrorBean errorBean) {

    }

    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String, String>> {// 统一下单

        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(PayActivity.this, getString(R.string.app_tip), getString(R.string.getting_prepayid));
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {
            if (dialog != null) {
                dialog.dismiss();
            }
            sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");

            resultunifiedorder = result;
            if (result.get("prepay_id") != null) {
                genPayReq();
            } else if (result.get("err_code_des") != null) {
                Toast.makeText(getApplicationContext(), result.get("err_code_des"), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getApplicationContext(), "调用微信支付失败！", Toast.LENGTH_SHORT).show();
            }

        }

        /**
         * 返回的数据是{result_code=SUCCESS,
         * sign=8942DE1F9ED323E465DFA24EBA2483CF,
         * mch_id=1380291302,
         * prepay_id=wx201608291743221cf913d1fa0982797606,
         * return_msg=OK, appid=wx3b9f4d39922b63d6,
         * nonce_str=zfkGIALKalDSLdZv,
         * return_code=SUCCESS,
         * trade_type=APP}
         */
        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();


            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            Map<String, String> xml = decodeXml(content);

            return xml;
        }
    }

    public Map<String, String> decodeXml(String content) {
        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            // 实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
        }
        return null;

    }

    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    private String genOutTradNo() {
        Random random = new Random();
//		String out_trade_no = MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
        String out_trade_no = orderResultBean.getOrder().getOrderNumber();
        return out_trade_no;
    }

    private String genProductArgs() {
        String body = "";
        if (!TextUtils.isEmpty(subject)) {
            if (subject.contains("subject=\"") && subject.contains("\"&body")) {
                int start = subject.indexOf("subject=\"");
                int end = subject.indexOf("\"&body");
                if (start + "subject=\"".length() < end) {
                    body = subject.substring(start + "subject=\"".length(), end);
                }
            }
        }
        if (TextUtils.isEmpty(body)) {
            body = "66商品";
        }
        StringBuffer xml = new StringBuffer();
        try {
            String nonceStr = genNonceStr();
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", APP_ID));
            packageParams.add(new BasicNameValuePair("body", body));
            packageParams.add(new BasicNameValuePair("mch_id", MCH_ID));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", "http://www.66wedding.com/"));
            packageParams.add(new BasicNameValuePair("out_trade_no", genOutTradNo()));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", getPhoneIp()));
            int totalPay = (int) ((StrUtil.floatNumDeal((float) orderResultBean.getOrder().getDm_TotalMoney())) * 100);
            packageParams.add(new BasicNameValuePair("total_fee", String.valueOf(totalPay)));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));

            String xmlstring = toXml(packageParams);
            return new String(xmlstring.getBytes(), "ISO8859-1");

        } catch (Exception e) {
            return null;
        }

    }

    private void genPayReq() {

        req.appId = APP_ID;
        req.partnerId = MCH_ID;
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());

        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);

        sb.append("sign\n" + req.sign + "\n\n");

        sendPayReq();
/**
 * 06626c742c7bc296cf4d4710e671a6ab
 */

    }

    /**
     * 生成签名
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(API_KEY);

        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return packageSign;
    }

    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(API_KEY);

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return appSign;
    }

    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");

            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        return sb.toString();
    }

    // 发起微信支付
    private void sendPayReq() {
        msgApi.registerApp(APP_ID);
        msgApi.sendReq(req);

    }

    public static String getPhoneIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
        }
        return "127.0.0.1";
    }

    /**
     * POST WeddingMobileApi/WXPayTrueSendMsg?Token={Token}
     * &out_trade_no={out_trade_no}&alipayJinE=
     * {alipayJinE}&wxPass={wxPass}
     * &buyer_id={buyer_id}&gmt_payment=
     * {gmt_payment}&trade_no={trade_no}&trade_status={trade_status}
     */

    public void getWedingdan() {
        String url = Url.WXPayTrueSendMsg + "out_trade_no=" + orderResultBean.getOrder().getOrderNumber() + "&alipayJinE=" + (StrUtil.floatNumDeal(orderResultBean.getOrder().getDm_TotalMoney())) + "&wxPass=" + md5 + "&buyer_id=" + "" +
                "&gmt_payment=" + refFormatNowDate() + "&trade_no=" + "" + "&trade_status=" + "true";
        Log.e("Log", "PayActivity getWedingdan: url="+url );
        HttpRequestBean requestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, WxremindBean.class, RequestCode.RETURN_PROCESS);
        HttpHandleUtil.executeCommonPost(this, requestBean);
    }

    /**
     * GET WeddingMobileApiSD/get_MD5Pass?Token={Token}&Pass={Pass}
     * 加密明文密码 返回加密后的MD5
     */
    private void get_MD5Pass() {
        String url = Url.GET_MD5PASS + "Pass=" + "22b63d6HT2F0WX689CCIT856";
        HttpRequestBean bottomListRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this, WXbean.class, RequestCode.GET_CASESLISTBYSEARCH);
        HttpHandleUtil.executeCommonGet(this, bottomListRequestBean);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEventMainThread(MessageEvent event) {
//        Log.e("Log", "PayActivity onEventMainThread: event="+event.getPayCode() );

        if (event.getPayCode() == 0) {
            getWedingdan();

        } else {

            finish();
        }
    }

    public String refFormatNowDate() {
        Date nowTime = new Date(System.currentTimeMillis());
        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
//        SimpleDateFormat sdFormatter = new SimpleDateFormat("yyyy-MM-ddTHH:mm:ss");
        String retStrFormatNowDate = sdFormatter.format(nowTime);
        return retStrFormatNowDate;
    }
    //


    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
           switch(msg.what){
               case GETRESULT:
                   getWedingdan();
                   break;

           }
        }
    };

}
